﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using HYView;

namespace YJKArch.WallModule
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdSetWallReJoin : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			if (CmdSetWallReJoin._hWndRevit == null)
			{
				CmdSetWallReJoin._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			CmdViewType types = (CmdViewType)11;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			Autodesk.Revit.DB.Document document = cmdData.Application.ActiveUIDocument.Document;
			Result result;
			try
			{
				if (cmdData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				this.m_Revit = cmdData;
				SetWallReJoinForm setWallReJoinForm = new SetWallReJoinForm(cmdData);
				setWallReJoinForm.Show(CmdSetWallReJoin._hWndRevit);
				int wMsg = 7;
				CmdSetWallReJoin.SendMessage(CmdSetWallReJoin._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
				Transaction transaction = null;
				transaction = new Transaction(document);
				transaction.Start("SetWallReJoin");
				try
				{
					WallJoinOperator wallJoinOperator = new WallJoinOperator();
					for (;;)
					{
						if (setWallReJoinForm.TheType == 0)
						{
							if (!wallJoinOperator.SetSingle(this.m_Revit, JoinType.ReJoin))
							{
								if (!setWallReJoinForm.PickButton)
								{
									break;
								}
								setWallReJoinForm.PickButton = false;
							}
						}
						else if (setWallReJoinForm.TheType == 1)
						{
							if (!wallJoinOperator.SetOne(this.m_Revit, JoinType.ReJoin))
							{
								if (!setWallReJoinForm.PickButton)
								{
									break;
								}
								setWallReJoinForm.PickButton = false;
							}
						}
						else if (!wallJoinOperator.SetMulti(this.m_Revit, JoinType.ReJoin))
						{
							if (!setWallReJoinForm.PickButton)
							{
								break;
							}
							setWallReJoinForm.PickButton = false;
						}
					}
				}
				catch (Exception)
				{
					if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
					{
						transaction.RollBack();
					}
					setWallReJoinForm.Close();
					return Autodesk.Revit.UI.Result.Failed;
				}
				transaction.Commit();
				setWallReJoinForm.Close();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				msg = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		public static WindowHandle _hWndRevit;

		private ExternalCommandData m_Revit;
	}
}
